Disons que j'ai quelque chose comme ça dans un fichier nommé main.js: function nom_obj () {} nom_obj.prototype = { toto: function () {alert ('salut!'); }, foo2: function () {alert ('salut encore!'); } } Maintenant, j'essaie de cette façon d'étendre l'objet dans un autre fichier extend.js: nom_obj.prototype = { newfoo: function () {alert ('salut # 3'); } } ... mais le problème est que cela fonctionnera simplement si je le code de cette façon: nom_obj.prototype.newfoo = function () {alert ('hi # 3'); } Je suppose que c'est peut-être une question noob. Je ne sais même pas si c'est la bonne façon d'étendre un objet, mais je panique ici en me demandant pourquoi cela se produit. Merci les gars d'avance.
2021-01-06 08:11:32
Dans un premier temps, vous remplacez le prototype par un nouveau (en écrasant ce qui existait auparavant). Dans un second temps, vous ajoutez un nouveau membre au prototype (et vous le développez ainsi). Il existe une autre méthode: une bibliothèque qui a une méthode extend ou similaire (qui encapsule essentiellement ce que vous faites dans votre deuxième formulaire dans un joli wrapper). Par exemple, dans jQuery: $ .extend (nom_obj.prototype, { newfoo: function () {alert ('salut # 3'); } } | Une autre option sans jQuery: var extend = fonction (destination, source) { for (propriété var dans la source) { if (destination [propriété] && (typeof (destination [propriété]) == 'objet') && (destination [propriété] .toString () == '[objet objet]') && source [propriété]) étendre (destination [propriété], source [propriété]); autre destination [propriété] = source [propriété]; } destination de retour; } var a = {a: 'test'}; // original var b = {newFoo: function () {alert ('hi # 3'); }}; // l'addition étendre (a, b); // étendre a.newFoo (); // appelle la propriété ajoutée | C'est parce que sur la ligne nom_obj.prototype = { newfoo: function () {alert ('salut # 3'); } } vous créez un nouvel objet prototype, supprimant le contenu privé. C'est comme si tu avais dit var a = {}; lorsque vous étendez un objet comme nom_obj.prototype.newfoo = function () {alert ('hi # 3'); } il ajoute simplement une nouvelle propriété (newfoo) à l'arborescence des objets en gardant le contenu existant intact. C'est pourquoi ça marche HTH Ivo Stoykov | Si vous recherchez une bibliothèque simple et légère qui vous donne exactement ceci: POO "bien fait" en javascript, jetez un œil à ceci: https://github.com/haroldiedema/joii Exemples de code source fournis dans le readme sur la page github, ainsi que ces liens: http://harold.info/projects/joii http://haroldiedema.github.io/joii Cette bibliothèque vous permet essentiellement de définir des «classes» comme telles: var Personne = Classe (fonction () { this.firstname = "Jean" this.surname = "Smith" this.role = "Développeur" this.getInfo = function () { return this.firstname + '' + this.surname + 'is' + this.role; }; }); var AnotherPerson = Classe ({étend: Personne}, function () { this.firstname = "Bob"; }); var p = nouveau AnotherPerson (); console.log (p.getInfo ()); // Bob Smith est développeur Éditer Pour prendre votre code comme exemple mais transformé en code compatible JOII, cela ressemblerait exactement à ceci: var nom_obj = Classe (fonction () { this.foo = function () {alert ('salut!'); }; this.foo2 = function () {alert ('salut encore!'); }; }; var obj_name2 = Classe ({étend: nom_obj}, function () { this.newfoo = function () {alert ('salut # 3'); }; }); var o = nouveau nom_obj2 (); o.foo (); // salut! o.newfoo (); // salut # 3 Ou utilisez-le comme mix-in: var o = nouveau nom_obj (); o.mixin (nom_obj2); o.newfoo (); // salut # 3 Ou l'inverse, en utilisant un «trait». // l'option "uses" copie essentiellement le contenu de l'objet donné dans la portée de votre "classe", résolvant le problème de réutilisation horizontale du code. var obj_name = Classe ({utilise: [obj_name2], function () { this.foo = function () {alert ('salut!'); }; this.foo2 = function () {alert ('salut encore!'); }; }); var o = nouveau nom_obj (); o.newfoo (); // salut # 3 | Ta Réponse StackExchange.ifUsing ("éditeur", fonction () { StackExchange.using ("externalEditor", function () { StackExchange.using ("extraits", function () { StackExchange.snippets.init (); }); }); }, "extraits de code"); StackExchange.ready (fonction () { var channelOptions = { tags: "" .split (""), id: "1" }; initTagRenderer ("". split (""), "" .split (""), channelOptions); StackExchange.using ("externalEditor", function () { // Doit lancer l'éditeur après les extraits, si les extraits sont activés if (StackExchange.settings.snippets.snippetsEnabled) { StackExchange.using ("extraits", function () { createEditor (); }); } autre { createEditor (); } }); function createEditor () { StackExchange.prepareEditor ({ useStacksEditor: faux, heartbeatType: 'réponse', autoActivateHeartbeat: faux, convertImagesToLinks: vrai, noModals: vrai, showLowRepImageUploadWarning: vrai, reputationToPostImages: 10, bindNavPrevention: vrai, suffixe: "", imageUploader: { brandingHtml: "Powered by \ u003ca href = \" https: //imgur.com/ \ "\ u003e \ u003csvg class = \" svg-icon \ "width = \" 50 \ "height = \" 18 \ "viewBox = \ "0 0 50 18 \" fill = \ "none \" xmlns = \ "http: //www.w3.org/2000/svg \" \ u003e \ u003cpath d = \ "M46.1709 9.17788C46.1709 8.26454 46.2665 7.94324 47.1084 7.58816C47.4091 7.46349 47.7169 7.36433 48.0099 7.26993C48.9099 6.97997 49.672 6.73443 49.672 5.93063C49.672 5.22043 48.9832 4.61182 48.1414 4.61182C47.4335 4.61182 46.72554.9762.6943 4.61182C47.4335 4.61182 46.72554.91628 46.094 4.69.4335 4.61182 46.72554.91628 46.094.49.48.4335 4.61182 46.7256 4.9762.692 43.1481 6.59048V11.9512C43.1481 13.2535 43.6264 13.8962 44.6595 13.8962C45.6924 13.8962 46.1709 13.2535 46.1709 11.9512V9.17788Z \ "/ \ u003e \ u003cpath d = \" M32.492 10.1419C32.492 12.6954.0 34184.01448.0 14.6954.0 34184.0 34184.0 14.6954.0 34184.0 14484.0 14.6954.0 34184.0 14484.0 41,5985 12,6954 41,5985 10,1419V6,59049C41,59855.28821 41.1394 4.66232 40.1061 4.66232C39.0732 4.66232 38.5948 5.28821 38.5948 6.59049V9.60062C38.5948 10.8521 38.2696 11.5455 37.0451 11.5455C35.8209 11.5455 35.4954 10.8521 35.4954 9.6006221.04.6904 10.8521 35.4954 9.6006221.04.6904 10.8521 35.4954 9.6006221.06.590 .1419Z \ "/ \ u003e \ u003cpath fill-rule = \" evenodd \ "clip-rule = \" evenodd \ "d = \" M25.6622 17.6335C27.8049 17.6335 29.3739 16.9402 30.2537 15.6379C30.8468 14.7755 30.9615 13.5579 30.9615 11.9512V6.59049C30.9615 5.28821 30.4833 4.66231 29.4502 4.66231C28.9913 4.66231 28.4555 4.94978 28.1109 5.50789C27.499 4.86533 26.7335 4.56087 25.7005 4.56087C23.1369 4.56087 21.0134 6.57349C28.9913 4.66231 28.4555 4.94978 28.1109 5.50789C27.499 4.86533 26.7335 4.56087 25.7005 4.56087C23.1369 4.56087 21.0134 6.57349C28.9913 4.66231 28.4555 4.94978 28.1109 5.50789C27.499 4.86533 26.7335 4.56087 25.7005 4.56087C23.1369 4.56087 21.0134 6.57349C 21.0132.00 13.9134.92134 9.24134 11.9134.92134 9.24134 11.9134.92134 13.9134 9,2134 9,2134 11,9134 9,2134 11,9134 9,2134 9,2134 11,9134 9,2134 9,2134 11,95 12.6616C28.1109 12.7229 28.1161 12.7799 28.121 12.8346C28.1256 12.8854 28.1301 12.9342 28.1301 12.983C28.1301 14.4373 27.2502 15.2321 25.777 15.2321C24.8349 15.2321 24.1352 14.9761823.566 37 14.5218C21.7977 14.5218 21.2429 15.0123 21.2429 15.6887C21.2429 16.7375 22.9072 17.6335 25.6622 17.6335ZM24.1317 9.27932C24.1317 7.94324 24.9928 7.09766 26.1024 7.09766C27.2119 7.09766 28.096.96 7.9187.9766C27.2119 7.09766 28.096.96 7.9187.9766C27.2119 7.09766 28.096.109.6324 24,1317 10,6491 24,1317 9,27932Z \ "/ \ u003e \ u003cpath d = \" M16.8045 11.9512C16.8045 13.2535 17.2637 13.8962 18.2965 13.8962C19.3298 13.8962 19.8079 13.2535 19.8079 11.9512V8.12928C19.8066 4.6669 4.6.4079 11.9512V8.12928C19.8066 4.6666.879 14,279 4,98375 13,3609 5,88013C12,653 5,05154 11,6581 4,62866 10,3573 4,62866C9,34336 4,62866 8,57809 4,89931 7,9466 5,5079C7,58314 4,9328 7,10506 4,66232 6,51203 4,66232C5.47873 4,66232 5.00066C 5,28866 5,48,2579 5,47873 4,66232 5 00066 C 5,28866 5,48,2579 5,4873 4,66232 5,00066 5,28866,2579 5,4873 4,66232 5,00066 5,28866,2579 5,4873 4,66232 5,00066 5,2862,8512 8.0232 13.2535 8.0232 11.9512V8.90741C8.0232 7.58817 8.44431 6.91179 9.53458 6.91179C10.5104 6.91179 10.893 7.58817 10.893 8.94108V11.9512C10.893 13.2535 11.3711 13.8962 12.4044 13.896 2C13.4375 13.8962 13.9157 13.2535 13.9157 11.9512V8.90741C13.9157 7.58817 14.3365 6.91179 15.4269 6.91179C16.4027 6.91179 16.8045 7.58817 16.8045 8.94108V11.9512Z \ "/ \ u003e \ u003cpath3 2.866" / M3903e \ u003cpath21 4.616 " 1,82471 4,66232C0,791758 4,66232 0,313354 5,28821 0,313354 6,59049V11,9512C0,313354 13,2535 0,791758 13,8962 1,82471 13,8962C2,85798 13,8962 3,31675 13,2535 3,31675 11,9512V6,59049Z \ "/ \ u003e \ u003e \ u00204,81cp = 0,412V6,59049Z \" / \ u003e \ u003e \ u00204,83cp = 0,4412,81 0 1.1159 0 1.98861C0 2.87869 0.822846 3.57676 1.87209 3.57676C2.90056 3.57676 3.7234 2.87869 3.7234 1.98861C3.7234 1.1159 2.90056 0.400291 1.87209 0.400291Z \ "fill = \" # 1BB76E \ "/ \ u003 / a \ u003c \ u003 \ u003e ", contentPolicyHtml: "Contributions des utilisateurs sous licence \ u003ca href = \" https: //stackoverflow.com/help/licensing \ "\ u003ecc by-sa \ u003c / a \ u003e \ u003ca href = \" https://stackoverflow.com / legal / content-policy \ "\ u003e (politique de contenu) \ u003c / a \ u003e", allowUrls: vrai }, onDemand: vrai, discardSelector: ".discard-answer" , immédiatementShowMarkdownHelp: true, enableTables: true, enableSnippets: true }); } }); Merci d'avoir répondu à Stack Overflow! Veuillez vous assurer de répondre à la question. Fournissez des détails et partagez vos recherches! Mais évitez… Demander de l'aide, des éclaircissements ou répondre à d'autres réponses. Faire des déclarations basées sur des opinions; les sauvegarder avec des références ou une expérience personnelle. Pour en savoir plus, consultez nos conseils sur la rédaction de bonnes réponses. Brouillon enregistré Brouillon rejeté Inscrivez-vous ou connectez-vous StackExchange.ready (fonction () { StackExchange.helpers.onClickDraftSave ('# login-link'); }); Inscrivez-vous avec Google Inscrivez-vous via Facebook Inscrivez-vous par e-mail et mot de passe Soumettre Publier en tant qu'invité Nom Email Obligatoire, mais jamais affiché StackExchange.ready ( fonction () { StackExchange.openid. , 'question_page'); } ); Publier en tant qu'invité Nom Email Obligatoire, mais jamais affiché Publiez votre réponse Jeter En cliquant sur «Publier votre réponse», vous acceptez nos conditions d'utilisation, notre politique de confidentialité et notre politique de cookies Ce n'est pas la réponse que vous recherchez? Parcourez les autres questions marquées javascript javascript-objects ou posez votre propre question.